package com.wandian.news.mvvm.lifetool.zgjm;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.JsonObject;
import com.mylib.libcore.data.TTBaseAppApi;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.news.bean.LifeZGJMBean;

import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.AppConfig.TOUTIAO_KEY;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_LIFE_ZGJM;


/**
 * @author Administrator
 * @date 2019/12/18-16:11
 * @description LifeZGJMActivityViewModel
 **/
public class LifeZGJMActivityViewModel extends BaseViewModel {
    private TTBaseAppApi baseAppApi;
    public MutableLiveData<List<LifeZGJMBean.NewslistBean>> dataBean =  new MutableLiveData<>();
    public LifeZGJMActivityViewModel(@NonNull Application application) {
        super(application);
        baseAppApi =  RetrofitUtil.getTouTiaoRetrofit().create(TTBaseAppApi.class);
    }

    public void getData(String searchName){

        showDialog();
        JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key",TOUTIAO_KEY);
        hashMap.put("num","20");
        hashMap.put("word",searchName);
        RxResultHelper.getHttpObservableNothing(getLifecycleProvider(), baseAppApi.getTouTiaoList(NEWS_LIFE_ZGJM,hashMap,jsonObject))
                .subscribe(new Observer<Object>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {
                        dismissDialog();
                        Log.d("getTouTiaoList-zgjm", JsonUtil.toJson(o)+"");
                        if(!UIUtils.isEmpty(o)){
                            LifeZGJMBean bean = JsonUtil.parseJsonToBean(JsonUtil.toJson(o),LifeZGJMBean.class);
                            if(!UIUtils.isEmpty(bean) && bean.getCode()==200 && !UIUtils.isEmpty(bean.getNewslist()) && bean.getNewslist().size()>0){
                                dataBean.setValue(bean.getNewslist());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        ToastUtil.show("网络错误");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

}
